<?php

/**
 * 环信 类
 */
namespace App\Service\Easemob;

use App\Service\Customer\CustomerTokenService;



class EasemobService
{
    /*参数*/
    private $client_id;
    private $client_secret;
    private $org_name;
    private $app_name;
    private $url;
    /**
     * 初始化参数
     * EasemobService constructor.
     */
    public function __construct()
    {
        $ease_config = config('easemob');
        $this->client_id = $ease_config['client_id'];
        $this->client_secret = $ease_config['client_secret'];
        $this->org_name = $ease_config['org_name'];
        $this->app_name = $ease_config['app_name'];

        if(!empty($this->org_name) && !empty($this->app_name)){
            $this->url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/';
        }
    }

    /**
     * 获得token
     */
    public function getToken()
    {
        $tk = CustomerTokenService::getToken('easemob_token');
        $nowtime = time();
        if(!$tk || $tk['token_expire']<=$nowtime){
            $options=array(
                "grant_type"=>"client_credentials",
                "client_id"=> $this->client_id,
                "client_secret" => $this->client_secret
            );
            $body=json_encode($options);
            $url=$this->url.'token';
            $tokenResult = $this->postCurl($url,$body,$header=array());
            $tk['uid'] = 'easemob_token';
            $tk['token'] = $tokenResult['access_token'];
            $tk['token_expire'] = $nowtime + $tokenResult['expires_in'];
            CustomerTokenService::setToken($tk['uid'], $tk['token'], $tk['token_expire']);
        }
        return $tk['token'];
    }

    /**
     * 用户注册
     */
    function registerEaseUser($username, $password, $nickname){
        $url = $this->url.'users';
        $options=array(
            "username" => $username,
            "password" => $password,
            "nickname" => $nickname
        );
        $body = json_encode($options);
        $header = array("Authorization:Bearer ".$this->getToken());
        $result = $this->postCurl($url,$body,$header);
        //var_dump($result);
        return $result['entities'];
    }

    /**
     * 发送透传
     */
    public function sendText($from = '',$target = array(), $body = '', $ext = array(),$type = 'text')
    {
        $url = $this->url.'message';
        $content = array(
            'target_type' => 'users',
            'target' => $target,
            'msg' => array(
                'type' => $type,
                'msg' => $body
            ),
            'from' => $from
        );

        if($ext){
            $content['ext'] = $ext;
        }

        $body = json_encode($content);
        //var_dump($body);
        $header = array("Authorization:Bearer ".$this->getToken());
        $result = $this->postCurl($url,$body,$header);
        //var_dump($result);
        return (isset($result['data']) && !empty($result['data'])) ? $result['data'] : false;
    }

    /**
     * 重新设置昵称
     */
    public function  setNickname($uid = '', $nickname = '')
    {
        $url = $this->url."users/{$uid}";
        $content = array(
            'nickname' => $nickname
        );
        $body = json_encode($content);
        $header = array("Authorization:Bearer ".$this->getToken());
        $result = $this->postCurl($url, $body, $header);
        //var_dump($result);
        return $result;
    }

    /**
     * curl post请求
     */
    public  function postCurl($url, $body, $header)
    {
        $ch = curl_init();
        //设置url
        curl_setopt($ch, CURLOPT_URL, $url);
        //post方式提交
        curl_setopt($ch,CURLOPT_POST,true);
        //设置头部请求
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求数据
        if (count($body) > 0) {
            //$b=json_encode($body,true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);//全部数据使用HTTP协议中的"POST"操作来发送。
        }
        //设置请求头
        if (count($header) > 0) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算
        //获得数据
        $res = curl_exec($ch);

        $result=json_decode($res,true);
        curl_close($ch);

        if(empty($result))
            return $res;
        else
            return $result;
    }
}